<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\AfterSaleOption;
use App\Product_order_after_sale;
use App\Product_sku;
use App\Product;
use App\Product_order;
use App\Shop;
use App\Member;
use App\Realname;
use App\Product_order_pro;
use App\AfterSaleAddress;
use App\AfterSaleItem;
use App\ShopHistory;

class AftersaleController extends AdminController
{

    private $_timeleave = 3 * 24 * 60 * 60;
 // 3天审核时间
    private $_daifa = 3 * 24 * 60 * 60;
 // 3天等待用户发货
    private $_shouhuo = 10 * 24 * 60 * 60;
 // 10天收货时间
    
    public static function run(){
        $af = new AftersaleController();
        $af->autoProcess();
    }
    
    /**
     * 超时关闭--每小时运行
     */
    public function autoProcess()
    {
        echo "\nBegin " . date('Y-m-d H:i:s') . "\n";
        // 申请退款——3天之后自动退款；
        // 申请退货退款——3天后自动发送退货地址；
        // 申请换货——3天后自动发送退货地址；
        $afterSales = Product_order_after_sale::where('status', 1)->where('created_at', '<', date('Y-m-d H:i:s', time() - $this->_timeleave))->get();
        foreach ($afterSales as $item) {
            if ($item->type == 1) {
                echo "审核超时: type:1, " . $item->id . "\n";
                $option = new AfterSaleOption();
                $option->after_id = $item->id;
                $option->admin_id = 0;
                $option->option_description = "审核超时，自动退款";
                if ($option->save()) {
                    $item->status = 2;
                    $item->save();
                    // 退款
                    $this->tuiKuan($item, $item->refund_price);
                }
            }
            
            if ($item->type == 2 || $item->type == 3) {
                echo "审核超时 type:" . $item->type . ', ' . $item->id . "\n";
                $option = new AfterSaleOption();
                $option->after_id = $item->id;
                $option->admin_id = 0;
                $option->option_description = "审核超时，自动分配收货地址";
                if ($option->save()) { 
                    $order = Product_order::withTrashed()->where('order_id', $item->order_id)->first();
                    $shop = Shop::where('member_id', $order->member_id)->first();//自动分配到商铺地址 
                    $add = $shop->after_address;
                    $uname = $shop->after_username;
                    $phn = $shop->after_userphone; 
                    
                    $afterDefalutAddr = AfterSaleAddress::where('shop_id', $order->member_id)->where('default', 1)->first();
                    
                    if($afterDefalutAddr){
                        $add = $afterDefalutAddr->address;
                        $uname = $afterDefalutAddr->username;
                        $phn = $afterDefalutAddr->userphone; 
                    }
                    
                    $address_id = 0;
                    $item->status = 4;
                    $item->address_id = $address_id;
                    $item->after_address = $add;
                    $item->after_username = $uname;
                    $item->after_userphone = $phn;
                    $item->save();
                }
            }
        }
        // 发送地址后 3天——等待用户发货
        $afterSales = Product_order_after_sale::where('status', 4)->where('invoice_no', '')
            ->where('updated_at', '<', date('Y-m-d H:i:s', time() - $this->_daifa))
            ->get();
        foreach ($afterSales as $item) {
            echo "收货超时3天未发货，自动关闭 type:" . $item->type . ', ' . $item->id . "\n";
            $option = new AfterSaleOption();
            $option->after_id = $item->id;
            $option->admin_id = 0;
            $option->option_description = "收货超时3天未发货，自动关闭";
            if ($option->save()) {
                $item->status = 3;
                $item->refuse_reason = '用户超时未发货';
                $item->save();
            }
        }
        
        // 发送地址后 10天——自动退款
        $afterSales = Product_order_after_sale::where('status', 4)->where('invoice_no','<>','')
            ->where('updated_at', '<', date('Y-m-d H:i:s', time() - $this->_shouhuo))
            ->get();
        foreach ($afterSales as $item) {
            echo "收货超时10天，自动退款 type:" . $item->type . ', ' . $item->id . "\n";
            $option = new AfterSaleOption();
            $option->after_id = $item->id;
            $option->admin_id = 0;
            $option->option_description = "收货超时10天，自动退款";
            if ($option->save()) {
                $item->status = 2;
                $item->save();
                // 退款
                $this->tuiKuan($item, $item->refund_price);
            }
        }
        
        echo "\nEnd " . date('Y-m-d H:i:s') . "\n";
    }

    // 待处理售后订单列表
    public function todo(Request $request)
    {
        $orderNo = trim($request->input('order_id', ''));
        $start = trim($request->input('start', ''));
        $end = trim($request->input('end', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        $fliter = Product_order_after_sale::where('status', '1');
        
        if ($start) {
            $fliter = $fliter->where('created_at', '>=', $start);
        }
        if ($end) {
            $fliter = $fliter->where('created_at', '<=', $end . ' 23:59:59');
        }
        if ($orderNo) {
            $fliter = $fliter->where('after_sale_no', 'like', "%" . $orderNo . "%");
        }
        $fliter->orderBy('id','desc');
        
        $columns = [
            'id',
            'create_time',
            'created_at',
//             'refund_id',
            'refund_price',
            'type',
            'goods_status',
            'reason',
//             'sku',
            'status',
            'after_sale_no',
            'refuse_reason',
//             'product_sku_id',
//             'product_id'
        ];
        $data = $fliter->paginate($pagenumber, $columns, 'page', $page + 1);
        
        $itemWithOther = array();
        $items = $data->items();
        foreach ($items as $item) {
//             $item['pname'] = $this->pname($item->product_sku_id, $item->product_id);
            $item['time_leave'] = $this->_timeleave - (time() - strtotime($item->created_at));
            if ($item['time_leave'] < 0)
                $item['time_leave'] = 0;
            
            if ($item->status == 4) {
                $item->status = 2;
            } elseif ($item->status == 1) {
                $item->status = 1;
            } else {
                $item->status = 3;
            }
            $item['order_id'] = $item->after_sale_no;
        }
        
        $this->output(array(
            "count" => $data->total(),
            "items" => $data->items(),
            "page" => $page
        ));
    }

    private function pname($sku, $pid)
    {
        $skuP = Product_sku::where('sku', $sku)->first();
        if ($skuP) {
            return $skuP->spec_name;
        }
        $product = Product::where('id', $pid)->first();
        if ($product) {
            return $product->name;
        }
        return '';
    }

    // 待处理售后订单列表
    public function alllist(Request $request)
    {
        $status = trim($request->input('status', ''));
        $orderNo = trim($request->input('order_id', ''));
        $start = trim($request->input('start', ''));
        $end = trim($request->input('end', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        $fliter = Product_order_after_sale::where('id', '>', '0');
        
        if ($start) {
            $fliter = $fliter->where('created_at', '>=', $start);
        }
        if ($end) {
            $fliter = $fliter->where('created_at', '<=', $end . ' 23:59:59');
        }
        if ($orderNo) {
            $fliter = $fliter->where('after_sale_no', 'like', "%" . $orderNo . "%");
        }
        if ($status == 1) {
            $status = '1';
            $fliter = $fliter->where('status', '1');
        }
        if ($status == 2) {
            $status = '4';
            $fliter = $fliter->where('status', '4');
        }
        if ($status == 3) {
            $fliter = $fliter->whereIn('status', array(
                2,
                3,
                5
            ));
        }
        $fliter->orderBy('id','desc');
        
        $columns = [
            'id',
            'created_at',
            'after_sale_no',
//             'refund_id',
            'refund_price',
            'type',
            'goods_status',
            'reason',
            'status',
//             'sku',
            'goods_status',
            'updated_at',
            'close_reason',
            'refuse_reason',
//             'product_sku_id',
//             'product_id'
        ];
        $data = $fliter->paginate($pagenumber, $columns, 'page', $page + 1);
        
        $itemWithOther = array();
        $items = $data->items();
        foreach ($items as $item) {
            // var_dump($item);
//             $item['pname'] = $this->pname($item->product_sku_id, $item->product_id);
            if (in_array($item->status, array(
                2,
                3,
                5
            ))) {
                $item['complatetime'] = date("Y-m-d H:i:s", strtotime($item->updated_at));
            } else {
                $item['complatetime'] = '';
            }
            if ($item->status == 3) {
                $item['closetype'] = '拒绝';
            } elseif ($item->status == 2) {
                $item['closetype'] = '同意';
            } else {
                $item['closetype'] = '';
            }
            if ($item->status == 4) {
                $item->status = 2;
            } elseif ($item->status == 1) {
                $item->status = 1;
            } else {
                $item->status = 3;
            }
            $item['order_id'] = $item->after_sale_no;
            // $item->created_at = date("Y-m-d", strtotime( $item->created_at) );
            // $item->updated_at = date("Y-m-d", strtotime( $item->updated_at) );
            
            $item['time_leave'] = $this->_timeleave - (time() - strtotime($item->created_at));
            if ($item['time_leave'] < 0)
                $item['time_leave'] = 0;
        }
        
        $this->output(array(
            "count" => $data->total(),
            "items" => $data->items(),
            "page" => $page
        ));
    }

    public function shenhe(Request $request)
    {
        $id = trim($request->input('id', ''));
        $afterSall = Product_order_after_sale::where('id', $id)->first();
        // 剩余时间
        $data = array();
        $data['time_leave'] = $this->_timeleave - (time() - strtotime($afterSall->created_at));
        if ($data['time_leave'] < 0)
            $data['time_leave'] = 0;
        // 售后详情
        $data['info'] = array(
            'id' => $afterSall->id,
            'type' => $afterSall->type,
            'goods_status' => $afterSall->goods_status,
            'reason' => $afterSall->reason,
            'reason2' => $afterSall->reason2,
            'refund_price' => $afterSall->refund_price,
            'images' => $afterSall->imgs,
            'max_price' => $afterSall->max_price
        );
        // 订单详情
        $order = Product_order::withTrashed()->where('order_id', $afterSall->order_id)->first();
        $seller = Shop::where('member_id', $order->member_id)->first();
        $member = Member::where('id', $order->buyer_id)->first();
        $real = Realname::where('member_id', $member->id)->first();
        $items = AfterSaleItem::where('after_sale_no', $afterSall->after_sale_no)->get();
        $productItem = array();
        foreach ($items as $item){
            $productItem[] = Product_order_pro::where('id', $item->order_pro_id)->first();
        }
        $data['order'] = array(
            'orderid' => $order->order_id,
            'company' => $seller->company,
            'ordercreatetime' => date('Y-m-d', strtotime($order->created_at)),
            'orderid' => $order->order_id,
            'orderstatus' => $order->status, // 订单状态：0 取消 1待付款 2待发货 3 待收货 4待评价 5退货 6失效
            'buyer_id' => $member->id,
            'buyer_realname' => $real->realname,
            'consignee_address' => $order->consignee_address,
            'logistics_name' => $order->logistics_name,
            'invoice_no' => $order->invoice_no,
            'logistics_price' => $order->logistics_price,
            'price_all' => $order->total_price,
            'product_price' => $order->product_price,
//             'product_price' => $productItem->price * $productItem->num,
            'pay_time' => date('Y-m-d H:i:s', $order->payment_time),
            'pay_type' => $order->payment_name,
            'productinfo' => $productItem
        );
        if ($afterSall->after_address) { 
            $data['address'] = array(
                'address'=>$afterSall->after_address,
                'username'=>$afterSall->after_username,
                'userphone'=>$afterSall->after_userphone
            );
        }
        //
        $this->output($data);
    }

    // 同意退款
    public function optrepay(Request $request)
    {
        $id = (int) trim($request->input('id', ''));
        $admin_id = (int) trim($request->input('admin_id', ''));
        $comments = trim($request->input('comments', ''));
        
        $amount = trim($request->input('amount', '0'));
        
        $afterSall = Product_order_after_sale::where('id', $id)->first();
        // 状态验证
        // if($afterSall->type == 1 && $afterSall->status==1){
        
        // }else{
        // $this->err("操作错误，该订单非退款");
        // }
        if($afterSall->refund_price == 0 ){
            if( $amount && $amount > $afterSall->max_price){ 
                $this->err("操作错误，退款金额大于".$afterSall->max_price);
            }
        }else if ($amount && $amount > $afterSall->refund_price) {
            $this->err("操作错误，退款金额大于".$afterSall->refund_price);
        }
        if ($afterSall->status == 2) {
            $this->err("已退款");
        }
        $option = new AfterSaleOption();
        $option->after_id = $id;
        $option->admin_id = $admin_id;
        $option->option_description = "同意退款操作, 备注：" . $comments;
        if ($option->save()) {
            $afterSall->status = 2;
            $afterSall->save();
            $this->tuiKuan($afterSall, $amount);
            $this->output(array(
                'status' => $afterSall->status
            ));
        } else {
            $this->err("操作记录失败");
        }
    }

    // 不同意退款-关闭申请
    public function optclose(Request $request)
    {
        $id = (int) trim($request->input('id', ''));
        $admin_id = (int) trim($request->input('admin_id', ''));
        $comments = trim($request->input('comments', ''));
        
        $afterSall = Product_order_after_sale::where('id', $id)->first();
        // 状态验证
        // if($afterSall->type == 1 && $afterSall->status==1){
        
        // }else{
        // $this->err("操作错误，该订单非退款");
        // }
        
        $option = new AfterSaleOption();
        $option->after_id = $id;
        $option->admin_id = $admin_id;
        $option->option_description = "关闭申请操作, 备注：" . $comments;
        if ($option->save()) {
            $afterSall->status = 3;
            $afterSall->close_reason = $comments;
            $afterSall->save();
            $this->output(array(
                'status' => $afterSall->status
            ));
        } else {
            $this->err("操作记录失败");
        }
    }

    // 选择收货地址
    public function optaddress(Request $request)
    {
        $id = (int) trim($request->input('id', ''));
        $admin_id = (int) trim($request->input('admin_id', ''));
        $address_id = (int) trim($request->input('address_id', ''));
        $afterSall = Product_order_after_sale::where('id', $id)->first();
        $add='';
        $uname='';
        $phn='';
        if(0==$address_id){ 
            $order = Product_order::where('order_id', $afterSall->order_id)->first();
            $shop = Shop::where('member_id', $order->member_id)->first();
            $add = $shop->after_address;
            $uname = $shop->after_username;
            $phn = $shop->after_userphone;
        }else{
            $adds = AfterSaleAddress::where('id', $address_id)->first();
            $add = $adds->address;
            $uname = $adds->username;
            $phn = $adds->userphone;
        }
        
        $option = new AfterSaleOption();
        $option->after_id = $id;
        $option->admin_id = $admin_id;
        $option->option_description = "选择收货地址操作, 备注：" . $address_id;
        if ($option->save()) {
            $afterSall->status = 4;
            $afterSall->address_id = $address_id;
            $afterSall->after_address = $add;
            $afterSall->after_username = $uname;
            $afterSall->after_userphone = $phn;
            $afterSall->save();
            $this->output(array(
                'status' => $afterSall->status,
                'address_id' => $afterSall->address_id
            ));
        } else {
            $this->err("操作记录失败");
        }
    }

    private function tuiKuan($atferObj, $amount)
    {
        // 实际退款逻辑，待做 #TODO
        $amount = $amount ? $amount : $atferObj->refund_price;
        
        $option = new AfterSaleOption();
        $option->after_id = $atferObj->id;
        $option->admin_id = 0;
        $option->option_description = "退款, 实际退款金额：" . $amount . ", 应退金额" . $atferObj->refund_price;
        if ($option->save()) {
            $order = Product_order::withTrashed()->where('order_id', $atferObj->order_id)->first();
            $quotePayNeedUpFanxian = false;
            if ($order->payment_code == 'quote_pay') {
                $quotePayNeedUpFanxian = true;
                // 信用支付
                if ($order->is_shop_jiesuan) {
                    // 订单已经结算给商铺
                } else {
                    // 订单没有已经结算给商铺
                }
            } elseif ($order->payment_code == 'amount_pay') {
                // 余额支付
                if ($order->is_shop_jiesuan) {
                    // 订单已经结算给商铺
                } else {
                    // 订单没有已经结算给商铺
                }
            } elseif ($order->payment_code == 'card_pay') {
                // 银行卡支付
                if ($order->is_shop_jiesuan) {
                    // 订单已经结算给商铺
                } else {
                    // 订单没有已经结算给商铺
                }
            }
            // 扣商家钱--------全扣商铺钱不完善，需要去掉返现再按照服务费比例扣 #TODO
            $memberShop = Member::where('id', $order->member_id)->first();
            //扣除服务费比例
            $shop = Shop::where('member_id', $order->member_id)->first();  
            $amount_shop = $amount - sprintf('%.2f', $amount * $shop->service_charge / 100 );
            
            $amountShangpu = $amount_shop;//扣除服务费比例之和的钱，参与退款
            
            updateAccountLog($memberShop->id, $memberShop->name, $amountShangpu, '订单退款给用户,退款记录' . $atferObj->after_sale_no, 11, 0, 99); // 商家退款手动减
            
            //加入商铺端资金日志
            $client = Realname::where('member_id', $order->buyer_id)->first();
            $shophistory = new ShopHistory();
            $shophistory->shop_id = $memberShop->id;
            $shophistory->client_member_id = $order->buyer_id;
            $shophistory->client_name = $client->realname;
            $shophistory->client_phone = $client->phone;
            $shophistory->trans_no = $order->order_id;
            $shophistory->amount = 0-$amountShangpu;
            $shophistory->channel = $order->payment_name;
            $shophistory->type = "订单退款";
            $shophistory->save();
                                                                                                                        
            // 退款给用户：
            $member = Member::where('id', $order->buyer_id)->first();
            updateAccountLog($member->id, $member->name, $amount, '订单退款,退款记录' . $atferObj->after_sale_no, 7, 0, 99); // 7-退款
            
            //处理返现逻辑
            if($quotePayNeedUpFanxian){
                if($order->fanxian_status == 0){
                    $afterItems = AfterSaleItem::where('after_sale_no', $atferObj->after_sale_no)->get();
                    $order_pro_id_tmp =  array();
                    foreach ($afterItems as $temp){
                        $order_pro_id_tmp[] = $temp->order_pro_id;
                    }
                    //把原本需要返现的，变成不需要返现
                    Product_order_pro::whereIn('id', $order_pro_id_tmp)->where('fanxian_status', 1)->update(['fanxian_status'=>0]);
                    
                    $fanxianAmount = Product_order_pro::where('order_id', $order->order_id)->where('fanxian_status', 1)->sum('fanxian_amount');
                    if(!$fanxianAmount){ 
                        $fanxianAmount = 0;
                    }
                    $order->fanxian_amount = $fanxianAmount;
                    $order->save();
                }
            }
            
            $this->changeOrderStatus($order->order_id);
        }
    }

    // 清单全部售后处理完成，修改订单为完成
    public function changeOrderStatus($orderid)
    {
        $orderAfterCount = Product_order_after_sale::where('order_id', $orderid)->whereIn('status', [
            2,
            5
        ])->count();
        $productsCount = Product_order_pro::where('order_id', $orderid)->count();
        if ($orderAfterCount == $productsCount) {
            $order = Product_order::where('order_id', $orderid)->first();
            $oldstatus = $order->status;
            $order->status = 5; //修改订单主表状态为完成
            
            if(in_array($oldstatus, array(2,3)) && $order->payment_code == 'quote_pay' && $order->fanxian_status != 1){
                //原来没有确认收货的单子，改成完成需要处理返现和结算
                $order->fanxian_amount = $this->fanxian($order);
                $order->fanxian_status = 1;//返现状态
            }
            
            $order->save();
            OrderJiesuanShop($order->order_id);//结算资金给商户
        }
        
        
        
    }

    // 待处理-获取头部
    public function todoheader(Request $request)
    {
        $id = (int) trim($request->input('id', ''));
        $afterSall = Product_order_after_sale::where('id', $id)->first();
        if ($afterSall->status != 4) {
            $this->err('非处理中订单');
        }
        $data = array();
        $headertype = 0;
        if (! $afterSall->invoice_no) {
            // 等待用户填写物流单号
            $headertype = 1;
            $desc = '';
            if ($afterSall->type == 2) {
                $desc = '退货退款';
            } elseif ($afterSall->type == 3) {
                $desc = '换货';
            }
            $data['desc'] = "您已同意买家的" . $desc . "申请，请您及时关注买家的发货信息，若买家超时未发货，该订单将自动关闭";
            $data['comments'] = $afterSall->reason . "; " . $afterSall->reason2 . '; ' . $afterSall->refuse_reason;
        }
        if ($afterSall->invoice_no) {
            // 待收货
            $headertype = 2;
            $data['invoice_no'] = $afterSall->invoice_no;
            $data['logistics_name'] = $afterSall->logistics_name;
            $data['time_leave'] = $this->_shouhuo - (time() - strtotime($afterSall->updated_at));
            if ($data['time_leave'] < 0)
                $data['time_leave'] = 0;
        }
        
        $this->output(array(
            'type' => $headertype,
            'data' => $data
        ));
    }

    // 已经收到货
    public function optshoudao(Request $request)
    {
        $id = (int) trim($request->input('id', ''));
        $admin_id = (int) trim($request->input('admin_id', ''));
        $comments = trim($request->input('comments', ''));
        $afterSall = Product_order_after_sale::where('id', $id)->first();
        $option = new AfterSaleOption();
        $option->after_id = $id;
        $option->admin_id = $admin_id;
        $option->option_description = "已经收到货, 备注：" . $comments."，新发货单号：".trim($request->input('back_logistics_name', '')).' '.trim($request->input('back_invoice_no', ''));
        if ($option->save()) {
            $afterSall->status = 5; // 换货不退款
            $afterSall->back_logistics_name = trim($request->input('back_logistics_name', ''));
            $afterSall->back_invoice_no = trim($request->input('back_invoice_no', ''));
            $afterSall->save();
            $this->changeOrderStatus($afterSall->order_id);
            $this->output(array(
                'status' => $afterSall->status
            ));
        } else {
            $this->err("操作记录失败");
        }
    }

    public function optlogs(Request $request)
    {
        $id = (int) trim($request->input('id', ''));
        $logs = AfterSaleOption::where('after_id', $id)->get();
        $this->output($logs);
    }

    public function statusinfo(Request $request)
    {
        $id = (int) trim($request->input('id', ''));
        $afterSall = Product_order_after_sale::where('id', $id)->first();
        // $afterSall
        $status = 3;
        if ($afterSall->status == 4) {
            $status = 2;
        } elseif ($afterSall->status == 1) {
            $status = 1;
        }
        $buyerfahuo = 0;
        if($afterSall->invoice_no){
            $buyerfahuo = 1;
        }
        
        $this->output(array(
            'status' => $status,
            'buyerfahuo' => $buyerfahuo,
            'type' => $afterSall->type
        ));
    }
}